package com.ccb.sc.auth;

import com.ccb.sc.login.service.IAppTokenService;
 import com.auth0.jwt.interfaces.Claim;
import com.ccb.sc.constant.AppConst;
import com.ccb.sc.common.util.HttpServletRequestUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author ken
 * @version 1.0
 * @date 2020-09-22
 */
@Component
public class TokenUtil {

    @Autowired
    private IAppTokenService appTokenService;

    private static IAppTokenService tokenService;

    @PostConstruct
    public void init(){
        tokenService = appTokenService;
    }

    /**
     * 从请求头或者请求参数中
     *
     * @return token
     */
    public static String getToken() {
        return getToken(HttpServletRequestUtil.getRequest());
    }

    /**
     * 从请求头或者请求参数中
     *
     * @param request request
     * @return token
     */
    public static String getToken(HttpServletRequest request) {
        if (request == null) {
            throw new IllegalArgumentException("request不能为空");
        }
        // 从请求头中获取token
        String token = request.getHeader(AppConst.TOKEN_HEAD_NAME);
        if (StringUtils.isBlank(token)) {
            // 从请求参数中获取token
            token = request.getParameter(AppConst.TOKEN_HEAD_NAME);
        }
        return token;
    }

    /**
     * 尝试从请求头获取当前登录用户id
     * 不一定能获取到memberId
     * @param request request
     * @return memberId
     */
    public static Long getMemberId(HttpServletRequest request) {
        String tokenStr = getToken(request);
        if (StringUtils.isBlank(tokenStr)) {
            return null;
        }
        Map<String, Claim> claims = JWTHelper.unSign(tokenStr);
        if (claims == null || !claims.containsKey(AppConst.MEMBER_SESSION_ATTR_KEY)) {
            return null;
        }
        Claim sessionKey = claims.get(AppConst.MEMBER_SESSION_ATTR_KEY);
        if (sessionKey == null) {
            return null;
        }
        Token token = tokenService.getTokenModel(sessionKey.asString());
        if (token == null) {
            return null;
        }
        return token.getMemberId();
    }

    public static String generateToken(Long memberId, String sessionKey) {
        Token tk = new Token();

        tk.setMemberId(memberId);
        tk.setRole("member");
        tk.setAttribute(AppConst.MEMBER_SESSION_ATTR_KEY, sessionKey);
        String key = tk.getTokenKey();
        String sign = JWTHelper.sign(memberId, AppConst.PREFIX_TOKEN_TYPE, key);
        tk.setSign(sign);
        //存入redis
        tokenService.storeToken(key, tk);
        return sign;
    }
}
